<script setup>
import { fetchDeliveryFeeList, saveDeliveryFee, deleteDeliveryFee } from '@/api/goodDeliveryFeeApi'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'
import AddDeliveryFee from './components/AddDeliveryFee.vue'

const dialogVisible = ref(false)
const currentDeliveryFeeId = ref('')
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

// 详情对话框
const detailVisible = ref(false)
const detailDeliveryFeeId = ref('')

// 审核对话框
const approvalDialogVisible = ref(false)
const approvalDeliveryFeeId = ref('')

// 查询条件
const queryFields = ref({
  documentNumber: '',
})

// 获取配送费列表
const getDeliveryFeeList = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        documentNumber: queryFields.value.documentNumber.trim() || null,
      },
    }

    const res = await fetchDeliveryFeeList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取配送费列表失败')
    }
  } catch (error) {
    logger.error('获取配送费列表失败', error)
    ElMessage.error('获取配送费列表失败')
  } finally {
    loading.value = false
  }
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getDeliveryFeeList()
}

// 每页条数改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getDeliveryFeeList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getDeliveryFeeList()
}

// 重置搜索
const handleReset = () => {
  queryFields.value = {
    documentNumber: '',
  }
  currentPage.value = 1
  getDeliveryFeeList()
}

// 打开新增对话框
const openAddDialog = () => {
  currentDeliveryFeeId.value = ''
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  currentDeliveryFeeId.value = row.updateShippingFeeMId
  dialogVisible.value = true
}

// 打开审核对话框
const openApprovalDialog = (row) => {
  approvalDeliveryFeeId.value = row.updateShippingFeeMId
  approvalDialogVisible.value = true
}

// 查看详情
const viewDetail = (row) => {
  detailDeliveryFeeId.value = row.updateShippingFeeMId
  detailVisible.value = true
}

// 操作处理
const handleAction = (command, row) => {
  switch (command) {
    case 'approval':
      openApprovalDialog(row)
      break
    case 'edit':
      openEditDialog(row)
      break
    case 'detail':
      viewDetail(row)
      break
    case 'delete':
      handleDeleteConfirm(row)
      break
  }
}

// 删除确认
const handleDeleteConfirm = (row) => {
  ElMessageBox.confirm(`确定要删除单据 '${row.documentNumber}' 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleDelete(row)
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 删除
const handleDelete = async (row) => {
  try {
    const res = await deleteDeliveryFee(row.updateShippingFeeMId)
    if (res.success) {
      ElMessage.success('删除成功')
      getDeliveryFeeList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    logger.error('删除失败', error)
    ElMessage.error('删除失败')
  }
}

// 确认审核（暂时保留，未来可能在子组件内部完成）
const handleApprovalConfirm = async () => {
  if (!approvalDeliveryFeeId.value) return
  try {
    loading.value = true
    // 这里直接提交审核，无需获取完整数据
    const payload = {
      updateShippingFeeMId: approvalDeliveryFeeId.value,
      editType: 2,
      isCheck: true,
    }
    const res = await saveDeliveryFee(payload)
    if (res.success) {
      ElMessage.success('审核成功')
      closeDialog()
      getDeliveryFeeList()
    } else {
      ElMessage.error(res.msg || '审核失败')
    }
  } catch (error) {
    logger.error('审核失败', error)
    ElMessage.error('审核失败')
  } finally {
    loading.value = false
  }
}

// 关闭所有对话框
const closeDialog = () => {
  dialogVisible.value = false
  detailVisible.value = false
  approvalDialogVisible.value = false
}

// 新增/编辑成功后的回调
const handleSuccess = () => {
  getDeliveryFeeList()
  closeDialog()
}

// 组件挂载时获取数据
onMounted(() => {
  getDeliveryFeeList()
})
</script>

<template>
  <!-- 详情对话框 -->
  <el-dialog
    v-model="detailVisible"
    title="配送费调价单详情"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddDeliveryFee
      v-if="detailVisible"
      :delivery-fee-id="detailDeliveryFeeId"
      is-preview
      @close="closeDialog"
    />
  </el-dialog>

  <!-- 审核对话框 -->
  <el-dialog
    v-model="approvalDialogVisible"
    title="审核配送费调价单"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddDeliveryFee
      v-if="approvalDialogVisible"
      :delivery-fee-id="approvalDeliveryFeeId"
      is-preview
      hide-footer
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" @click="handleApprovalConfirm">
          <template #icon>
            <el-icon><LineMdCheckAll /></el-icon>
          </template>
          审核通过
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增/编辑配送费对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentDeliveryFeeId ? '编辑配送费调价单' : '新增配送费调价单'"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddDeliveryFee
      :delivery-fee-id="currentDeliveryFeeId"
      @success="handleSuccess"
      @close="closeDialog"
    />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields" @submit.prevent="handleSearch">
          <el-form-item label="单据号">
            <el-input
              v-model="queryFields.documentNumber"
              placeholder="请输入单据号"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            新增运费调价单
          </el-button>
        </el-form-item>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="tableData" v-loading="loading" row-key="updateShippingFeeMId">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="documentNumber" label="单据号" min-width="150" align="center" />
        <el-table-column label="单据时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.documentTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="dealer"
          label="供应商"
          min-width="200"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column prop="operatorName" label="操作人" width="100" align="center" />
        <el-table-column label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isCheck ? 'success' : 'warning'">
              {{ row.isCheck ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkerName" label="审核人" width="100" align="center">
          <template #default="{ row }">
            {{ row.checkerName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ row.checkTime ? formatDateTime(row.checkTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="notes"
          label="备注"
          min-width="120"
          :show-overflow-tooltip="true"
          align="center"
        >
          <template #default="{ row }">
            {{ row.notes || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-dropdown
              @command="(command) => handleAction(command, row)"
              :show-timeout="100"
              :hide-timeout="100"
            >
              <el-button type="primary" size="small">
                操作
                <template #icon>
                  <el-icon><LineMdGrid3 /></el-icon>
                </template>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="!row.isCheck" command="approval">
                    <el-icon><LineMdCheckAll /></el-icon>
                    审核
                  </el-dropdown-item>
                  <el-dropdown-item command="edit" :disabled="row.isCheck">
                    <el-icon><LineMdEdit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="detail">
                    <el-icon><LineMdWatchLoop /></el-icon>
                    详情
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="row.isCheck">
                    <el-icon><LineMdTrash /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[15, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}

.mr-2 {
  margin-right: 0.5rem;
}
.ml-2 {
  margin-left: 0.5rem;
}
</style>
